package io.renren.modules.erp.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * s
 * 
 * @author bob_ye
 *
 */
public class ExportExcelUtil {

	private static Logger logger = LoggerFactory.getLogger(ExportExcelUtil.class);

	public static void outputExcel(HttpServletRequest request, HttpServletResponse response, List<List<String>> excelList, String fileNameCn,
			String fileNameEn) {

		String fileName = null;
		try {
		    String userAgent = request.getHeader("user-agent");  
            if (userAgent != null && userAgent.indexOf("Firefox") >= 0 || userAgent.indexOf("Chrome") >= 0   
                    || userAgent.indexOf("Safari") >= 0) {  
                fileName = new String(fileNameCn.getBytes(), "ISO8859-1");  
            } else {  
                fileName=URLEncoder.encode(fileNameCn,"UTF8"); //其他浏览器  
            }  
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}

		response.reset();
		response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		InputStream excelFile = ExportExcelUtil.class.getResourceAsStream("/" + fileNameEn);

		try {

			Workbook workbook = new HSSFWorkbook(excelFile);
			Sheet sheet = workbook.getSheetAt(0);

			int rowNum = 1;
			for (List<String> li : excelList) {
				Row row = sheet.createRow(rowNum++);
				int index = 0;
				for (String s : li) {
					row.createCell(index++).setCellValue(s);
				}
			}

			OutputStream output = response.getOutputStream();
			workbook.write(output);
			output.flush();
			output.close();

			workbook.close();

		} catch (final IOException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}
}
